package org.ymx.myArrayList.algorithm;

import org.ymx.myArrayList.MyArrayList;

/**
 * @author 17122
 */
public class SearchAlgorithm {

    /**
     * 二分查找
     *
     * @param array  将要被查找的数组
     * @param target 目标元素
     * @return 返回目标元素位置
     */
    public static int binarySearch(MyArrayList<Integer> array, int target) {
        int left = 0;
        int right = array.size() - 1;
        int mid;
        while (left <= right) {
            mid = (left + right) / 2;
            if (array.get(mid) == target) {
                return mid;
            } else if (array.get(mid) < target) {
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }

    /**
     * 线性查找 时间复杂度n
     *
     * @param array  将要被查找的数组
     * @param target 目标元素
     * @return 返回目标元素位置
     */
    public static int search(MyArrayList<Integer> array, int target) {
        //遍历数组
        for (int i = 0; i < array.size(); i++) {
            if (array.get(i) == target) {
                return i;
            }
        }
        //没有找到对应的元素
        return -1;
    }

    public static void main(String[] args) {
        MyArrayList<Integer> list = new MyArrayList<>();
        list.add(1);
        list.add(2);
        list.add(4);
        list.add(5);
        list.add(7);
        System.out.println(binarySearch(list, 4));
        System.out.println(search(list,4));
    }

}


